'use strict'
let fs = require('fs'),
    router = require('koa-router')(),
    path = require('path');

function findFile(path) {
    let files = fs.readdirSync(path)
    return files.filter(x => {
        return x.endsWith('.js') && x !== 'index.js'
    })
}

function rou(files, dir) {
    files.forEach(element => {
        let filePath = path.join(dir, element);
        let router_fn = require(filePath);
        for (let x in router_fn) {
            let arr = router_fn[x];
            let type = router_fn[x][0];
            if (type === 'get') {
                let fn = arr[1];
                router.get(x, fn);
            } else {
                let fn = arr[1];
                router.post(x, fn);
            }
        }
    });
}

module.exports = function (dir) {
    let workDir = dir || 'controllers';
    let workPath = path.resolve('.');
    let realRouter = path.join(workPath, workDir);
    let jsFile = findFile(realRouter);
    rou(jsFile, realRouter);
    return router.routes();
}